package com.innerchic.sponsor.builder;

import com.innerchic.sponsor.other.Subject;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 订阅方法查找类
 */
public class SubMethodFind {

    private final Map<Class<?>, List<SubObject>> searchMethodCache;

    public SubMethodFind() {
        searchMethodCache = new ConcurrentHashMap<>();
    }

    /**
     * 查找订阅方法
     * 优先使用缓存
     *
     * @param object 对象
     * @return 订阅对象集
     */
    public List<SubObject> findSubMethod(Object object) {
        if (object == null) return new ArrayList<>();
        if (!searchMethodCache.containsKey(object.getClass())) {
            searchMethod(object);
        }
        return searchMethodCache.get(object.getClass());
    }

    /**
     * 搜索当前对象的订阅方法并缓存
     *
     * @param object 对象
     */
    private void searchMethod(Object object) {
        if (object == null) return;
        Class<?> aClass = object.getClass();
        List<SubObject> cacheMethods = new ArrayList<>();
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            Subject subject = declaredMethod.getAnnotation(Subject.class);
            if (subject == null) continue;
            declaredMethod.setAccessible(true);
            SubObject subObject = new SubObject(subject, declaredMethod, aClass.getName());
            cacheMethods.add(subObject);
        }
        searchMethodCache.put(aClass, cacheMethods);
    }

}
